﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace NextCommerce.Web.Templates.XmlRepository {

	public class XmlRepository : ITemplateRepository {

		private readonly IConfiguration _configuration;

		public XmlRepository(IConfiguration configuration) {
			_configuration = configuration;
		}

		public ITemplate GetTemplate(string name) {
			var templateElement = GetTemplatesElement()[name];
			if (templateElement != null) {
				return GetTemplate(templateElement);
			} else {
				throw new ArgumentException(string.Format("The template '{0}' was not found", name), "name");
			}
		}

		public IEnumerable<ITemplate> GetAll() {
			return GetTemplatesElement().Cast<XmlElement>().Select(GetTemplate);
		}

		private XmlElement GetTemplatesElement() {
			var xmlDocument = new XmlDocument();
			xmlDocument.Load(_configuration.TemplatesXmlFile);
			var templates = xmlDocument.DocumentElement;
			if (templates != null && templates.Name == "templates" && templates.HasChildNodes) {
				return templates;
			}
			throw new Exception("The templates xml file is not valid");
		}

		private ITemplate GetTemplate(XmlElement templateElement) {
			return new Template(templateElement.Name, templateElement.InnerXml);
		}

	}

}
 